package com.biz.primus.ms.cart.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.common.utils.DateUtil;
import com.biz.primus.ms.cart.dao.ro.ShopCartItemRo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.stream.Collectors;

import static com.google.common.collect.Lists.newArrayList;

/**
 * 购物车redis操作dao
 *
 * @author lei
 * @date 2017/01/11
 */
@Repository("shopCartRedisDao")
public class ShopCartItemRedisDao extends CrudRedisDao<ShopCartItemRo, String> {

    /**
     * 保存购物车明细
     *
     * @param ro 优惠券ro
     */
    @Override
    public void save(ShopCartItemRo ro) {
        ro.setId(getId(ro.getUserId(), ro.getProductCode()));
        ro.setUpdateTimestamp(DateUtil.now());
        super.save(ro);
    }

    /**
     * 批量保存购物车明细
     *
     * @param ros
     */
    public void save(List<ShopCartItemRo> ros) {
        if (CollectionUtils.isNotEmpty(ros)) {
            this.save(ros);
        }
    }

    /**
     * 批量移除购物车商品
     *
     * @param userId       用户Id
     * @param productCodes 商品编码集合
     */
    public void deleteByUserIdAndProductCodes(Long userId, Collection<String> productCodes) {
        if (userId == null || CollectionUtils.isEmpty(productCodes)) {
            return;
        }
        List<String> ids = Optional.of(productCodes).orElse(new ArrayList<>())
                .stream().filter(StringUtils::isNotBlank).map(code -> getId(userId, code)).collect(Collectors.toList());
        super.pipleDelete(ids);
        List<byte[]> collect = ids.stream().map(RedisUtil::toByteArray).collect(Collectors.toList());
        super.zrem(this.getUserIdToShopCartProductIdSortedSetKey(userId), RedisUtil.ListBytetoByteArray(collect));
    }

    /**
     * 生成id (memberId:productCode)
     *
     * @param userId
     * @param productCode
     * @return
     */
    private String getId(Long userId, String productCode) {
        return String.format("%s:%s", userId, productCode);
    }

    /**
     * 根据用户Id查询购物车商品明细
     *
     * @param userId
     * @return
     */
    public ShopCartItemRo findByUserIdAndProductCode(Long userId, String productCode) {
        return findOne(getId(userId, productCode));
    }

    /**
     * 根据用户Id查询购物车商品明细
     *
     * @param userId
     * @return
     */
    public List<ShopCartItemRo> findByUserId(Long userId) {
        Set<byte[]> idBytes = super.zrevrange(getFieldSortedSetKey("memberId", userId), 0, -1L);
        if (CollectionUtils.isNotEmpty(idBytes)) {
            return findByIds(idBytes);
        } else {
            return newArrayList();
        }
    }


    private String getUserIdToShopCartProductIdSortedSetKey(Long userId) {
        return getKeyByParams("memberId", userId);
    }


}
